package com.ruoyi.customer.service.impl;

import java.util.List;
import java.util.Random;

import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.PrimaryKeyIdUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.ip.IpUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.customer.api.domain.WxLoginBody;
import com.ruoyi.customer.domain.CustomerBindVO;
import com.ruoyi.customer.domain.CustomerDeviceBindVO;
import com.ruoyi.customer.domain.PersonalInfo;
import com.ruoyi.customer.mapstruct.CustomerMapper;
import com.ruoyi.customer.service.ICustomerBindService;
import com.ruoyi.device.mapper.DeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.customer.mapper.CustomerManagementMapper;
import com.ruoyi.customer.api.domain.CustomerManagement;
import com.ruoyi.customer.service.ICustomerManagementService;

/**
 * 客户管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-03
 */
@Service
public class CustomerManagementServiceImpl implements ICustomerManagementService 
{
    @Autowired
    private CustomerManagementMapper customerManagementMapper;

    @Autowired
    private ICustomerBindService customerBindService;

    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询客户管理
     * 
     * @param id 客户管理主键
     * @return 客户管理
     */
    @Override
    public CustomerManagement selectCustomerManagementById(Long id)
    {
        return customerManagementMapper.selectCustomerManagementById(id);
    }

    /**
     * 查询客户管理列表
     * 
     * @param customerManagement 客户管理
     * @return 客户管理
     */
    @Override
    public List<CustomerManagement> selectCustomerManagementList(CustomerManagement customerManagement)
    {
        return customerManagementMapper.selectCustomerManagementList(customerManagement);
    }

    /**
     * 新增客户管理
     * 
     * @param customerManagement 客户管理
     * @return 结果
     */
    @Override
    public int insertCustomerManagement(CustomerManagement customerManagement)
    {
        customerManagement.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
        customerManagement.setCreateTime(DateUtils.getNowDate());
        return customerManagementMapper.insertCustomerManagement(customerManagement);
    }

    /**
     * 修改客户管理
     * 
     * @param customerManagement 客户管理
     * @return 结果
     */
    @Override
    public int updateCustomerManagement(CustomerManagement customerManagement)
    {
        customerManagement.setUpdateTime(DateUtils.getNowDate());
        return customerManagementMapper.updateCustomerManagement(customerManagement);
    }

    /**
     * 批量删除客户管理
     * 
     * @param ids 需要删除的客户管理主键
     * @return 结果
     */
    @Override
    public int deleteCustomerManagementByIds(Long[] ids)
    {
        return customerManagementMapper.deleteCustomerManagementByIds(ids);
    }

    /**
     * 删除客户管理信息
     * 
     * @param id 客户管理主键
     * @return 结果
     */
    @Override
    public int deleteCustomerManagementById(Long id)
    {
        return customerManagementMapper.deleteCustomerManagementById(id);
    }

    /**
     * 校验客户账号是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkAccountUnique(CustomerManagement user)
    {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        CustomerManagement info = customerManagementMapper.checkCustomerAccountUnique(user.getAccount());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 注册客户信息
     * @param customerManagement
     * @return
     */
    @Override
    public Boolean registerCustomer(CustomerManagement customerManagement) {
        customerManagement.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
        return customerManagementMapper.insertCustomerManagement(customerManagement)>0;
    }

    @Override
    public CustomerManagement selectCustomerByAccount(String account) {
        return customerManagementMapper.selectCustomerByAccount(account);
    }

    @Override
    public Boolean updateCustomerProfile(CustomerManagement customerManagement) {
        return customerManagementMapper.updateCustomerManagement(customerManagement)>0;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(CustomerManagement user)
    {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        CustomerManagement info = customerManagementMapper.checkPhoneUnique(user.getPhoneNumber());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean checkEmailUnique(CustomerManagement currentUser) {
        Long userId = StringUtils.isNull(currentUser.getId()) ? -1L : currentUser.getId();
        CustomerManagement info = customerManagementMapper.checkEmailUnique(currentUser.getEmail());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateCustomerStatus(CustomerManagement user)
    {
        return customerManagementMapper.updateCustomerManagement(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean updateUserProfile(CustomerManagement user)
    {
        return customerManagementMapper.updateCustomerManagement(user) > 0;
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateCustomerAvatar(String userName, String avatar)
    {
        return customerManagementMapper.updateCustomerAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(CustomerManagement user)
    {
        return customerManagementMapper.updateCustomerManagement(user);
    }

    @Override
    public CustomerManagement getCustomerInfoByOpenId(WxLoginBody wxLoginBody) {
        String openId = wxLoginBody.getOpenId();
        //先判断是否存在该手机号的用户,看看是否要融合
        CustomerManagement customerManagement = customerManagementMapper.selectWxUserByOpenIdOrPhoneNumber(openId,wxLoginBody.getPhoneNumber());
        if (customerManagement==null) {
            CustomerManagement insert = new CustomerManagement();
            insert.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
            insert.setOpenId(openId);
            insert.setCreateTime(DateUtils.getNowDate());
            String stringRandom = getStringRandom(16);
            String nickName = wxLoginBody.getUserInfo().getNickName()+stringRandom;
            insert.setNickName(nickName);
            insert.setAccount(nickName);
            insert.setRealName(nickName);
            insert.setPhoneNumber(wxLoginBody.getPhoneNumber());
            insert.setAvatar(wxLoginBody.getUserInfo().getAvatarUrl());
            customerManagementMapper.insertCustomerManagement(insert);
            return insert;
        }else if (StringUtils.isNull(customerManagement.getOpenId())){
            customerManagement.setOpenId(openId);
            //customerManagement.setNickName(wxLoginBody.getUserInfo().getNickName());
            customerManagement.setUpdateTime(DateUtils.getNowDate());
            customerManagement.setLoginDate(DateUtils.getNowDate());
            customerManagement.setLoginIp(IpUtils.getIpAddr());
            customerManagementMapper.updateCustomerManagement(customerManagement);
        }
        //todo: 有可能openid不一致
        return customerManagement;

    }

    @Override
    public List<CustomerManagement> selectUnBindCustomerList(CustomerManagement customerManagement) {
        return customerManagementMapper.selectUnBindCustomerList(customerManagement);
    }

    @Override
    public PersonalInfo getPersonalInfo(Long id) {
        CustomerManagement customerManagement = selectCustomerManagementById(id);
        PersonalInfo personalInfo = CustomerMapper.INSTANCE.customerManagemtnToPersonalInfo(customerManagement);  ;
        CustomerBindVO customerBindVO = new CustomerBindVO();
        customerBindVO.setCustomerId(id);
        List<CustomerBindVO> customerBindVOS = customerBindService.selectCustomerBindList2(customerBindVO);
        personalInfo.setCustomerBindList(customerBindVOS);
        CustomerDeviceBindVO customerDeviceBindVO = new CustomerDeviceBindVO();
        customerDeviceBindVO.setCustomerId(id);
        List<CustomerDeviceBindVO> customerDeviceBindVOS = deviceMapper.selectCustomerDeviceBindList(customerDeviceBindVO);
        personalInfo.setCustomerDeviceBindList(customerDeviceBindVOS);
        return personalInfo;
    }

    @Override
    public CustomerManagement selectCustomerManagementByPhoneNumber(String phoneNumber) {
        return customerManagementMapper.selectCustomerManagementByPhoneNumber(phoneNumber);
    }

    @Override
    public int setDefaultDept(Long deptId) {
        CustomerManagement customerManagement = new CustomerManagement();
        customerManagement.setId(SecurityUtils.getUserId());
        customerManagement.setDeptId(deptId);
        customerManagement.setUpdateTime(DateUtils.getNowDate());
        customerManagement.setUpdateBy(SecurityUtils.getUsername());
        return customerManagementMapper.updateCustomerManagement(customerManagement);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetCustomerPwd(String userName, String password)
    {
        return customerManagementMapper.resetCustomerPwd(userName, password);
    }

    //生成随机用户名，数字和字母组成,
    public static String getStringRandom(int length) {

        String val = "";
        Random random = new Random();

        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }


}
